package site.luojie.transfer.dao.impl;

import site.luojie.transfer.dao.AccountDao;
import site.luojie.domain.Account;
import site.luojie.utils.ConnectionUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @Description: 用户数据访问层实现类
 * @Author jie.luo
 * @Create: 2020-04-30 22:58
 **/
public class JdbcAccountDaoImpl implements AccountDao {

    private ConnectionUtils connectionUtils;

    @Override
    public Account selectAccountByNumber(String number) throws Exception {
        Connection connection = connectionUtils.getCurrentThreadConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("select * from account where number = ?");
        preparedStatement.setObject(1, number);
        ResultSet resultSet = preparedStatement.executeQuery();
        Account account = null;
        while (resultSet.next()) {
            account = new Account();
            account.setId(resultSet.getInt("id"));
            account.setNumber(resultSet.getString("number"));
            account.setBalance(resultSet.getInt("balance"));
        }
        resultSet.close();
        preparedStatement.close();
        return account;
    }

    @Override
    public int updateAccountBalance(Account account) throws Exception {
        Connection connection = connectionUtils.getCurrentThreadConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("update account set balance = ? where id = ?");
        preparedStatement.setInt(1, account.getBalance());
        preparedStatement.setInt(2, account.getId());
        int row = preparedStatement.executeUpdate();
        preparedStatement.close();
        return row;
    }

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }
}
